# -*- coding: utf-8 -*-
import os
import re
import sys

pkg_root = os.path.realpath(os.path.join(os.path.realpath(__file__),
                                         os.path.pardir,
                                         os.path.pardir))
sys.path.append(pkg_root)

from common.file_utils import *

FINAL_MD_FILE_NAME = "Android.md"
MD_FILE_NAME_PREFIX_PATTERN = "^\d*"
MD_FILE_PATH_SEARCH_PATTERN = "\d+"


def merge(root_dir):
    merged_file = root_dir + "/" + FINAL_MD_FILE_NAME
    split = "\r\n\r\n"

    delete_file(merged_file)

    def choose_func(file_path, file_name):
        return True if os.path.isfile(file_path) and file_name.endswith(
            ".md") and re.match(MD_FILE_NAME_PREFIX_PATTERN, file_name).group(0) else False

    def sort_key(f):
        return int(re.findall(MD_FILE_PATH_SEARCH_PATTERN, f)[0])

    files = list_all_files(root_dir, choose_func, sort_key)

    length = write_file(merged_file, merge_all_files_content(files, split))
    print("merge content length=" + str(length))


if __name__ == '__main__':
    print('sys path=' + str(sys.path))
    print('current dir=' + os.path.abspath(os.curdir))
    print('py file dir=' + sys.path[0])
    print('py file path=' + os.path.abspath(__file__))
    # print('py file path=' + sys.argv[0])
    # print('py file path=' + __file__)
    print("\r")

    print("ls " + sys.path[0] + ":")
    os.system("ls " + sys.path[0])
    print("\r")

    if len(sys.argv) > 1:
        print('received arg=' + sys.argv[1])
        merge(sys.argv[1])
    else:
        merge(sys.path[0] + "/")
